home *** CD-ROM | disk | FTP | other *** search
- Path: news.ahc.ameritech.com!datalytics!news
- From: Rob Stewart <stew@datalytics.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Creating a pointer to a function "void (*ptrFunction)()" inside a class
- Date: 8 Jan 1996 17:35:42 GMT
- Organization: Datalytics, Inc
- Message-ID: <4crkle$h4r@gold.datalytics.com>
- References: <30ECA10F.3D99@ifu.net>
- NNTP-Posting-Host: pc071.datalytics.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.22 (Windows; I; 32bit)
-
- Jason Gresh <gresh@ifu.net> wrote:
- > I am trying to create a base class that has a function that the
- >derived class needs to create. In order to do this, I want to create a
- >pointer to a function in the base class that the derived class can then
- >define. This is not a case where an override will work because the
- >number and names of the derived functions is not known. >
- >class BaseClass
- >{
- > int (*ptrFunction)();
- >}
- >class DerivedClass : BaseClass
- >{
- > DerivedClass::DerivedClass();
- > int myFunction(int, int);
- >}
- >DerivedClass::DerivedClass()
- >{
- > ptrFunction = myFunction;
- >}
- >DerivedClass::myFunction(int, int)
- >{
- >// code ....
- >}
- >If I don't make myFunction part of the derived class (global),
- >everything works fine. As soon as I include it in the class, I cannot
- >assign a pointer to it. I am aware that pointers to functions inside
- >the class include the class name in some way ( this is not an issue for
- >global functions). What is the casting (or other) mechanism to make
- >this work?
- >
- This behavior will only work for static member functions. By
- declaring a member function static, you are asking the
- compiler to avoid mangling the name.
-
- On the other hand, by making a member function static, you
- lose the this pointer in the function call and the member
- function can no longer operate on an instance of the class.
- If you wish to restore that capability, you must pass a this
- pointer explicitly. That is, the function can take a pointer
- to the appropriate class parameter.
-
- If that "this" pointer is to be of a specific type (to match
- the member function's derived type, you'll need to use RTTI to
- validate that the "this" pointer is of the correct type. (The
- function pointer type will necessarily take a pointer to the
- base class, as must the derived class member functions. If
- you need a derived class pointer, you need to determine if a
- cast to the desired derived type is valid. RTTI is the only
- way to do that--whether you or the compiler implements RTTI is
- moot.)
-
- --
- Robert Stewart | My opinions are usually my own.
- Datalytics, Inc.
- (513)226-7700
- stew@datalytics.com
-
-
-